package com.a3dweijing.wetouch2.Activity;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Util.ImageLoaderUtil;
import com.a3dweijing.wetouch2.adapter.VideoDiscissRecAdapter;
import com.a3dweijing.wetouch2.base.BaseActivity;
import com.a3dweijing.wetouch2.bean.DiscussMsg;
import com.a3dweijing.wetouch2.bean.ExpoonVideo;
import com.a3dweijing.wetouch2.bean.FlagMag;
import com.a3dweijing.wetouch2.datainterface.Getdataimpl;
import com.a3dweijing.wetouch2.datasave.Singleton;
import com.a3dweijing.wetouch2.divView.CircleImageView;
import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by yxd on 2017/12/5.
 */

public class VideoPlayActivity extends BaseActivity {
    private String url="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private MediaPlayer player;
    private TextView name,like,play,timetxt;
    private CircleImageView userhead;
    private ProgressBar loading;
    private ImageView play_pasue,sceen,back;
    private SeekBar play_progress;
    private int sw,sh;
    private LinearLayout parentlayout,list_status;
    private RelativeLayout play_control;
    private Handler handler;
    private boolean flag=true;
    private SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
    private ExpoonVideo video;
    private RecyclerView discuss_list;
    private EditText input_discuss;
    @Override
    protected void onCreate( Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
        );
        setContentView(R.layout.activity_video_play_for_tv);
        name= (TextView) findViewById(R.id.video_play_videoname);
        like= (TextView) findViewById(R.id.video_play_like_count);
        play= (TextView) findViewById(R.id.video_play_play_count);
        userhead= (CircleImageView) findViewById(R.id.video_play_user_head);
        loading= (ProgressBar) findViewById(R.id.loading);
        play_pasue= (ImageView) findViewById(R.id.play_pause);
        sceen= (ImageView) findViewById(R.id.fill_sceen);
        play_progress= (SeekBar) findViewById(R.id.play_progress);
        parentlayout= (LinearLayout) findViewById(R.id.parentlayout);
        play_control= (RelativeLayout) findViewById(R.id.play_contro);
        timetxt= (TextView) findViewById(R.id.time_text);
        discuss_list= (RecyclerView) findViewById(R.id.video_discuss_list);
        list_status= (LinearLayout) findViewById(R.id.resaut_status);
        input_discuss= (EditText) findViewById(R.id.video_play_discuss);
        input_discuss.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (event.getAction())
                {
                    case KeyEvent.ACTION_DOWN:
                        String content=input_discuss.getText().toString().trim();
                        if (content!=null && content.length()>0){
                            new SetVideoDiscussThread(content).start();
                        }else
                        {
                            Toast.makeText(getBaseContext(),"评论不能为空", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }

                return true;
            }
        });
        discuss_list.setLayoutManager(new LinearLayoutManager(getBaseContext()));
        play_pasue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (player.isPlaying())
                {
                    player.pause();
                    play_pasue.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable.partition_video_play));
                }else
                    {
                        player.start();
                        play_pasue.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable.partition_video_pause));
                    }
            }
        });
        sceen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i = getResources().getConfiguration().orientation;
                if (i == Configuration.ORIENTATION_PORTRAIT) {
                    VideoPlayActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    ViewGroup.LayoutParams lp = surfaceView.getLayoutParams();
                    lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
                    surfaceView.setLayoutParams(lp);
                }else {
                    VideoPlayActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    ViewGroup.LayoutParams lp = surfaceView.getLayoutParams();
                    lp.width=sw;
                    lp.height=sh;
                    Log.e("--", "onClick: "+sw+":"+sh);
                    surfaceView.setLayoutParams(lp);
                }
            }
        });

        back= (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        video= (ExpoonVideo) getIntent().getSerializableExtra("video");
        if (video!=null)
        {
            name.setText(video.getVideoName());
            like.setText(video.getLikeCount()+"");
            play.setText(video.getClickNum()+"");
            ImageLoaderUtil.getLoader().loadImg4(Singleton.getInstance().getUser().getUser_head(),userhead);
            if (video.getVideoUrl()!=null && video.getVideoUrl().length()>10)
            {
                url="http://wetouch.oss-cn-hangzhou.aliyuncs.com/upload/"+video.getVideoUrl();
            }
        }

        Log.e("-----", "onCreate: "+url);
        surfaceView= (SurfaceView) findViewById(R.id.video_play_for_tv);
        surfaceHolder=surfaceView.getHolder();
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        Bundle b= (Bundle) msg.obj;
                        play_progress.setProgress(b.getInt("progress"));
                        timetxt.setText(b.getString("time"));
                        break;
                    case 100:
                        DiscussMsg discussmsg=new Gson().fromJson( msg.obj.toString(),DiscussMsg.class);
                        if (discussmsg!=null && discussmsg.isFlag())
                        {
                            if (discussmsg.getDiscussVideoList()!=null && discussmsg.getDiscussVideoList().size()>0)
                            {
                                list_status.setVisibility(View.GONE);
                                discuss_list.setAdapter(new VideoDiscissRecAdapter(discussmsg.getDiscussVideoList()));
                            }else
                                {
                                    list_status.setVisibility(View.VISIBLE);
                                }
                        }else
                            {
                                list_status.setVisibility(View.VISIBLE);
                            }
                        break;
                    case 200:
                        FlagMag flagmsg=new Gson().fromJson(msg.obj.toString(),FlagMag.class);
                        if (flagmsg.isFlag())
                        {
                            input_discuss.setText("");
                            new GetVideoDiscussThread().start();
                            Toast.makeText(getBaseContext(),"评论成功", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 404:
                        break;
                }
            }
        };
        surfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (back.getVisibility()== View.GONE)
                {
                    back.setVisibility(View.VISIBLE);
                    play_control.setVisibility(View.VISIBLE);
                }else {
                    back.setVisibility(View.GONE);
                    play_control.setVisibility(View.GONE);
                }
            }
        });
        new GetVideoDiscussThread().start();
    }
    @Override
    protected void onStart() {
        super.onStart();
        player=new MediaPlayer();
        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                player.setDisplay(holder);
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });
        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.e("--", "onPrepared: " );
                play_progress.setMax(mp.getDuration());
                int w=mp.getVideoWidth();
                int h=mp.getVideoHeight();
                if (w>h)
                {
                    int lw=parentlayout.getWidth();
                    sw=lw;
                    sh= (int) (lw/(w/(h*1.0)));
                    Log.e("--", "PreparedListener: "+sw+":"+sh);
                    RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(sw,sh);
                    surfaceView.setLayoutParams(lp);
                }
                player.start();
                player.setLooping(true);
                loading.setVisibility(View.GONE);
                new seekThread().start();
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus)
        {
            try {
                player.setDataSource(this, Uri.parse(url));
                player.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        flag=false;
        if (player!=null && player.isPlaying())
        {
            player.pause();
            player.stop();
            player.release();
        }else
            {
                player.release();
            }
    }
    class seekThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (flag)
            {
                int sb_progress =player.getCurrentPosition();
                String sd = sdf.format(new Date(player.getDuration()-sb_progress));   // 时间戳转换成时间
                Message m=handler.obtainMessage(1);
                Bundle b=new Bundle();
                b.putString("time",sd);
                b.putInt("progress",sb_progress);
                m.obj=b;
                handler.sendMessage(m);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private class GetVideoDiscussThread extends Thread {

        @Override
        public void run() {
            super.run();
            String resulet = new Getdataimpl().remoteGetDiscuss("1","2",video.getW_video_id()+"","0");
            Log.e("--", resulet);
            if (resulet != null && resulet.length() > 7) {
                handler.sendMessage(handler.obtainMessage(100, resulet));
            } else {
                handler.sendMessage(handler.obtainMessage(404, "网络繁忙，请稍后再试"));
            }
        }
    }
    private class SetVideoDiscussThread extends Thread {
        String content;

        public SetVideoDiscussThread(String content) {
            this.content = content;
        }

        @Override
        public void run() {
            super.run();
            String resulet = new Getdataimpl().remoteSetDisCuss(
                    "2", "0", video.getW_video_id()+"",
                    Singleton.getInstance().getUser().getUser_id(),
                    "1",content);
            Log.e("--", resulet);
            if (resulet != null && resulet.length() > 7) {
                handler.sendMessage(handler.obtainMessage(200, resulet));
            } else {
                handler.sendMessage(handler.obtainMessage(404, "网络繁忙，请稍后再试"));
            }
        }
    }
}
